'''
Created on Jul 9, 2011

@author: kafkef
'''

import sys
import traceback

from PyQt4.QtGui import *
from PyQt4.QtCore import QObject, SIGNAL, SLOT, pyqtSlot, Qt


from dexen.system.common import service
from dexen.system.client import ui

svr_proxy = ui.svr_proxy

class ConnectionWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        
        # creating widget objects
        self._label = QLabel("Server Addr:")
        self._line_edit = QLineEdit(service.get_my_ip())
        self._button = QPushButton("Connect")
        self._button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        
        # laying out children widgets
        h_layout = QHBoxLayout()
        
        h_layout.addWidget(self._label)
        h_layout.addWidget(self._line_edit)
        h_layout.addWidget(self._button)
        
        self.setLayout(h_layout)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        
        # signal/slot connection
        QObject.connect(self._button, SIGNAL("clicked()"),                               
                        self, SLOT("on_button_clicked()"))
        
    @pyqtSlot()
    def on_button_clicked(self):
        try:
            self.setCursor(QCursor(Qt.WaitCursor))
            svr_proxy.connect(str(self._line_edit.text()))
        except:
            traceback.print_tb(sys.exc_info()[2])
            print "Connection is failed"
            msg_box = QMessageBox(self)
            msg = "Cannot access the dexen server.\n"
            msg += "Make sure the address is valid and the server is running." 
            msg_box.setText(msg)
            msg_box.exec_()
        else:
            self.emit(SIGNAL("server_connected()"))
            self._button.setText("Connected")
            self._button.setEnabled(False)
            self._line_edit.setEnabled(False)
            #self.hide()
        finally:
            self.setCursor(QCursor(Qt.ArrowCursor))